from django import forms
from django.http import request
from web import models
from web.forms.bootstrap import BootStrapForm
from utils.tencent.cos import check_file

        
class FolderModelForm(BootStrapForm, forms.ModelForm):
    name = forms.CharField(
        label='文件夹名称',
        widget=forms.TextInput())
    class Meta:
        model = models.FileRepository
        fields=['name',]
        
        
    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj
        
    def clean_name(self):
        name = self.cleaned_data['name']
        fid = self.request.POST.get('fid','')
            # 当前目录的文件夹是否存在
        queryset = models.FileRepository.objects.filter(name=name,file_type=2,
                project=self.request.tracer.project)
        if fid.isdecimal():
            # 编辑目录,去除掉自己
            queryset = queryset.exclude(id=fid)
            
        if self.parent_obj:
            existed = queryset.filter(parent=self.parent_obj).exists()
        else:
            existed = queryset.filter(parent__isnull=True).exists()
                
        if existed:
            self.add_error('name', '文件夹重复')
        return name


class FileModelForm(forms.ModelForm):
    """Used to recieve data from Front end"""
    etag = forms.CharField(label='etag',max_length=128)
    class Meta:
        model = models.FileRepository
        exclude = ['project','file_type','update_user','update_datetime']
    
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
    def clean_file_path(self):
        file_path = "https://{}".format(self.cleaned_data['file_path'])
        return file_path
    def clean(self):
        etag = self.cleaned_data['etag']
        key = self.cleaned_data['key']
        file_size = self.cleaned_data['file_size']
        bucket = self.request.tracer.project.bucket
        region = self.request.tracer.project.region
        response = check_file(bucket,region,key) 
        print(response)
        if (etag!=response['ETag']):
            self.add_error('etag','etag不匹配')
        elif (file_size!=int(response['Content-Length'])):
            self.add_error('file_size','文件大小不一致')

        # 测试
        # self.add_error('file_size','文件大小不一致')

        return self.cleaned_data